const { createCanvas, loadImage } = require('canvas');
const path = require('path');
const fs = require('fs').promises;

/**
 * 生成滑块验证码
 */
async function generateCaptchaImage() {
  const bigWidth = 320;
  const bigHeight = 160;

  const puzzleWidth = 50; // 滑块主矩形宽度（不包含凸起）
  const puzzleHeight = 50; // 滑块高度
  const tabRadius = 10; // 凸起半径
  const fullPuzzleWidth = puzzleWidth + tabRadius;

  // 创建大图画布
  const bigCanvas = createCanvas(bigWidth, bigHeight);
  const bigCtx = bigCanvas.getContext('2d');

  // 加载背景图
  try {
    const bgDir = path.join(__dirname, '../images/captcha');
    const files = await fs.readdir(bgDir);
    const images = files.filter(f => /\.(jpg|jpeg|png)$/i.test(f));
    if (images.length === 0) throw new Error('No background image found');
    const bgPath = path.join(bgDir, images[Math.floor(Math.random() * images.length)]);
    const bgImg = await loadImage(bgPath);
    bigCtx.drawImage(bgImg, 0, 0, bigWidth, bigHeight);
  } catch {
    const r = Math.floor(Math.random() * 256);
    const g = Math.floor(Math.random() * 256);
    const b = Math.floor(Math.random() * 256);
    bigCtx.fillStyle = `rgb(${r},${g},${b})`;
    bigCtx.fillRect(0, 0, bigWidth, bigHeight);
  }

  // 添加浅色渐变
  const gradient = bigCtx.createLinearGradient(0, 0, 0, bigHeight);
  gradient.addColorStop(0, 'rgba(0,0,0,0.1)');
  gradient.addColorStop(1, 'rgba(255,255,255,0.1)');
  bigCtx.fillStyle = gradient;
  bigCtx.fillRect(0, 0, bigWidth, bigHeight);

  // 随机位置，避免贴边
  const padding = 10;
  const posX = Math.floor(Math.random() * (bigWidth - fullPuzzleWidth - padding * 2)) + padding;
  const posY = Math.floor(Math.random() * (bigHeight - puzzleHeight - padding * 2)) + padding;

  // 统一画路径函数（含凸起）
  function drawPuzzlePath(ctx, x, y, width, height, radius) {
    const centerY = y + height / 2;
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x + width, y);
    ctx.lineTo(x + width, centerY - radius);
    ctx.arc(x + width, centerY, radius, -Math.PI / 2, Math.PI / 2, false);
    ctx.lineTo(x + width, y + height);
    ctx.lineTo(x, y + height);
    ctx.closePath();
  }

  // 大图中绘制缺口
  bigCtx.save();
  drawPuzzlePath(bigCtx, posX, posY, puzzleWidth, puzzleHeight, tabRadius);
  bigCtx.fillStyle = 'rgba(50, 50, 50, 0.5)';
  bigCtx.fill();
  bigCtx.strokeStyle = '#ffffff';
  bigCtx.lineWidth = 1;
  bigCtx.stroke();
  bigCtx.restore();

  // 创建滑块图
  const smallCanvas = createCanvas(fullPuzzleWidth, puzzleHeight);
  const smallCtx = smallCanvas.getContext('2d');

  // 剪裁滑块路径
  drawPuzzlePath(smallCtx, 0, 0, puzzleWidth, puzzleHeight, tabRadius);
  smallCtx.clip();

  // 从大图中剪下滑块图像（包含凸起部分）
  smallCtx.drawImage(bigCanvas, posX, posY, fullPuzzleWidth, puzzleHeight, 0, 0, fullPuzzleWidth, puzzleHeight);

  // 添加边框阴影
  smallCtx.shadowColor = 'rgba(0,0,0,0.3)';
  smallCtx.shadowBlur = 4;
  smallCtx.lineWidth = 1;
  smallCtx.strokeStyle = '#ffffff';
  drawPuzzlePath(smallCtx, 0, 0, puzzleWidth, puzzleHeight, tabRadius);
  smallCtx.stroke();

  return {
    bigImageBase64: bigCanvas.toDataURL('image/png').split(',')[1],
    smallImageBase64: smallCanvas.toDataURL('image/png').split(',')[1],
    posX,
    posY,
    bigWidth,
    bigHeight,
    smallWidth: fullPuzzleWidth,
    smallHeight: puzzleHeight
  };
}
/**
 * 验证滑块位置
 */
function verifyCaptchaPosition(userX, realX, tolerance = 15) {
  // 调整为 15 像素
  return Math.abs(userX - realX) <= tolerance;
}

module.exports = { generateCaptchaImage, verifyCaptchaPosition };
